import Vue from 'vue';
import messageVue from './Message.vue';
let MessageContent = Vue.extend(messageVue);

let content, promise, time;
let option = {};

let Message = {
    success: function(msg) {
        option = {
            type: 'success',
            msg
        }
        createContent(option); 
    },
    error: function(msg) {
        option = {
            type: 'error',
            msg
        }
        createContent(option);
    },
    warning: function(msg) {
        option = {
            type: 'warning',
            msg
        }
        createContent(option);
    },
    success1: function(msg) {
        option = {
            type: 'success1',
            msg
        }
        createContent(option);
    },
    error1: function(msg) {
        option = {
            type: 'error1',
            msg
        }
        createContent(option);
    },
}

let createContent = (option) => {

    if (content) DestroyNow(content);

    content = new MessageContent({
        el: document.createElement('div'),
        data: {
            ...option,
            callback: defaultCallback
        }
    })

    document.body.appendChild(content.$el);
    // content.vm = content.$mount();
    Vue.nextTick(() => {
        content.visible = true;
    });

    close();
    if (typeof Promise !== 'undefined') {
        return new Promise((resolve, reject) => {
            promise = {
                resolve,
                reject
            }
        });
    } else {
        promise = option.callback
    }
}

let close = () => {
    if (!content) {
        return;
    }
    if (time) clearTimeout(time);
    time = setTimeout(() => {
        content.visible = false;
    }, 1500)
}

const defaultCallback = action => {
    let callback = promise.callback;
    if (typeof callback === 'function') {
        callback(action);
    }
    if (promise.resolve) {
        if (action === 'confirm') {
            promise.resolve(action);
        } else {
            promise.reject(action);
        }
    }
};

const DestroyNow = (content) => {
    content.$el.remove();
    content.$destroy(true);
    content = null;
}

export default Message